package com.itheima.record.controller;

import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.record.pojo.FieldRecord;
import com.itheima.record.service.FieldRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author
 * @since 2020-10-11
 */
@RestController
@RequestMapping("/record")
public class FieldRecordController {

    @Autowired
    private FieldRecordService fieldRecordService;

    /**
     * 提交业务处理:
     *     1.接受参数后,不存入数据库,保存到redis当中
     *     2.对于表格对应实体类数据,用redis hash进行存储
     * @param fieldRecord
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody FieldRecord fieldRecord){
        if (fieldRecord == null){
            return new Result(false, StatusCode.ERROR,"表单不能为空");
        }
       try {
           fieldRecordService.add(fieldRecord);

           return new Result(true,StatusCode.OK,"新增表单成功");
       }catch (Exception e){
           e.printStackTrace();
           return new Result(false,StatusCode.ERROR,"新增表单失败");
       }
    }


    /**
     * 修改业务:
     *      1.进行更改后,我先删除redis的数据,然后再添加
     * @param fieldRecord
     * @param date
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody FieldRecord fieldRecord,String date){
        if (fieldRecord == null){
            return new Result(false,StatusCode.ERROR,"表单不能为空");
        }
        try {
            fieldRecordService.update(date,fieldRecord);

            return new Result(true,StatusCode.OK,"表单修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"表单修改失败");
        }
    }


    /**
     * 提交业务:
     *     1.根据日期,为什么不用id呢,用户提交的时候没有id,用日期作为识别标识
     *     2.用redis取出来后,用户点击提交,直接存储到数据库中.
     * @param date
     * @return
     */
    @PostMapping("/commit")
    public Result commit( String date){
        if (date == null){
            return new Result(false,StatusCode.ERROR,"日期不能为空");
        }
        try {
            fieldRecordService.commit(date);
            return new Result(true,StatusCode.OK,"表单提交成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"表单提交失败");
        }
    }

    /**
     * 查看日报:
     *     提交日报后,就可以展示当天的日报
     * @param date
     * @return
     */
    @GetMapping("/findByDate/{date}")
    public Result findByDate(@PathVariable String date){
        if (date == null){
            return new Result(false,StatusCode.ERROR,"日期不能为空");
        }
        try {
            FieldRecord fieldRecord = fieldRecordService.find(date);
            return new Result(true,StatusCode.OK,"查看成功",fieldRecord);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"查看失败");
        }
    }
}

